package com.hethongviet.job.pages;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.hethongviet.job.AppMain;
import com.hethongviet.job.Config;
import com.hethongviet.job.Connectivity;
import com.hethongviet.job.R;
import com.hethongviet.job.helpers.CodeResult;
import com.hethongviet.job.helpers.ServiceHelper;
import com.hethongviet.job.helpers.database.ReportSQLite;
import com.hethongviet.job.helpers.sound.RecorderWave;
import com.hethongviet.job.helpers.sound.SoundPlay;
import com.hethongviet.job.models.FileGeneral;
import com.hethongviet.job.models.FileImage;
import com.hethongviet.job.models.Report;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap.CompressFormat;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class AddReportActivity extends Activity
{
	private EditText _editTextContent = null;
	private TextView _textImageStatus = null;

	private Button _buttonImage = null;
	private Button _buttonImageAgain = null;

	private Button _buttonAudioRecord = null;
	private Button _buttonAudioRecordStop = null;
	private Button _buttonAudioRecordAgain = null;
	private Button _buttonAudioRecordPlay = null;
	private Button _buttonAudioRecordPlayStop = null;
	private TextView _textTimeRecordCountDown = null;

	private RecorderWave _audioRecorder = null;

	private FileGeneral _fileAudioGeneral = null;
	private FileImage _fileImage = null;

	private Timer _timerStopPlayAudio = null;

	private Spinner _SpinnerSalesmanOutLet = null;
	private Spinner _SpinnerSalesmanPurpose = null;
	private Spinner _SpinnerSalesmanProduct = null;
	private Spinner _SpinnerSalesmanAmountOrder = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		/* Full screen */
		AppMain.prepareWindow(this);

		setContentView(R.layout.page_add_report);

		AppMain.showTaskTitle(this);

		_editTextContent = (EditText) findViewById(R.id.editTextCommentContent);

		_textImageStatus = (TextView) findViewById(R.id.textCommentAddImageStatus);
		_buttonImage = (Button) findViewById(R.id.buttonCommentAddImage);
		_buttonImageAgain = (Button) findViewById(R.id.buttonCommentAddImageAgain);

		_buttonAudioRecord = (Button) findViewById(R.id.buttonCommentAddRecord);
		_buttonAudioRecordAgain = (Button) findViewById(R.id.buttonCommentAddRecordAgain);
		_buttonAudioRecordPlay = (Button) findViewById(R.id.buttonCommentAddRecordPlay);
		_buttonAudioRecordStop = (Button) findViewById(R.id.buttonCommentAddRecordStop);
		_buttonAudioRecordPlayStop = (Button) findViewById(R.id.buttonCommentAddRecordPlayStop);
		_textTimeRecordCountDown = (TextView) findViewById(R.id.textAddCommentTimeRecordCountDown);

		_SpinnerSalesmanAmountOrder = (Spinner) findViewById(R.id.salesmanSpinnerAmount);
		_SpinnerSalesmanOutLet = (Spinner) findViewById(R.id.salesmanSpinnerOutlet);
		_SpinnerSalesmanProduct = (Spinner) findViewById(R.id.salesmanSpinnerProduct);
		_SpinnerSalesmanPurpose = (Spinner) findViewById(R.id.salesmanSpinnerPurpose);

		String[] outlets = { "outlet 1", "outlet 2", "outlet 3", "outlet 4",
				"outlet 5" };
		ArrayAdapter<String> outletArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, outlets);
		outletArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		_SpinnerSalesmanOutLet.setAdapter(outletArrayAdapter);

		String[] products = { "product 1", "product 2", "product 3",
				"product 4", "product 5" };
		ArrayAdapter<String> productArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, products);
		productArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		_SpinnerSalesmanProduct.setAdapter(productArrayAdapter);

		String[] purposes = { "purpose 1", "purpose 2", "purpose 3",
				"purpose 4", "purpose 5" };
		ArrayAdapter<String> purposeArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, purposes);
		purposeArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		_SpinnerSalesmanPurpose.setAdapter(purposeArrayAdapter);

		_buttonImage.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				/* Just choose image */
				if (_fileImage != null)
				{
					AppMain._imageFileView = _fileImage;
					Intent intent = new Intent(AddReportActivity.this,
							ViewImageActivity.class);
					intent.putExtra("request_type", AppMain.REQUEST_VIEW_IMAGE);
					startActivityForResult(intent, AppMain.REQUEST_VIEW_IMAGE);

				}
				else
					AppMain.showDialogList(AddReportActivity.this,
							AppMain.DIALOG_CHOOSING_IMAGE);
			}
		});

		_buttonImageAgain.setOnClickListener(new OnClickListener()
		{

			public void onClick(View arg0)
			{
				AppMain.showDialogList(AddReportActivity.this,
						AppMain.DIALOG_CHOOSING_IMAGE);
			}
		});

		_textImageStatus.setVisibility(View.VISIBLE);
		_buttonImage.setText(getString(R.string.textChoosingImage));
		_buttonImage.setVisibility(View.VISIBLE);

		if (Config.USE_AUDIO_RECORD)
		{
			_buttonAudioRecord.setVisibility(View.VISIBLE);
			_buttonAudioRecord.setOnClickListener(new OnClickListener()
			{
				public void onClick(View arg0)
				{

					if (!Config.USE_AUDIO_RECORD_BUILD_IN)
					{
						_audioRecorder = new RecorderWave();
					}

					if (Config.USE_AUDIO_RECORD_BUILD_IN)
					{
						Intent intent = new Intent(
								MediaStore.Audio.Media.RECORD_SOUND_ACTION);
						startActivityForResult(intent,
								AppMain.REQUEST_AUDIO_RECORD);
					}
					else
					{
						try
						{
							_audioRecorder.startRecording();
						} catch (Exception e)
						{
							e.printStackTrace();
							return;
						}

						_textTimeRecordCountDown.setVisibility(View.VISIBLE);

						new CountDownTimer(RecorderWave.MAX_RECORD_TIME, 1000)
						{

							@Override
							public void onTick(long millisUntilFinished)
							{
								_textTimeRecordCountDown.setText(getStringTimeShow(millisUntilFinished));
							}

							@Override
							public void onFinish()
							{
								_textTimeRecordCountDown.setVisibility(View.GONE);
								AppMain._codeResultService = CodeResult.STOP_RECORD_AUDIO;
								AppMain.callOnWindowFocusChange(AddReportActivity.this);
								return;
							}
						}.start();

						_buttonAudioRecord.setVisibility(View.GONE);

						_buttonAudioRecordStop.setVisibility(View.VISIBLE);
						_buttonAudioRecordStop.setOnClickListener(new OnClickListener()
						{
							public void onClick(View arg0)
							{
								try
								{
									// _audioRecorder.stop();
									// _audioRecorder.release();

									_audioRecorder.stopRecording();
								} catch (Exception e)
								{
									AppMain._codeResultService = CodeResult.SD_CARD_NOT_FOUND;
									AppMain.callOnWindowFocusChange(AddReportActivity.this);
									e.printStackTrace();
									return;
								}

								_buttonAudioRecordStop.setVisibility(View.GONE);
								_textTimeRecordCountDown.setVisibility(View.GONE);

								if (getAudioInputStream() == null)
								{
									return;
								}

								/* Permit re-record */
								// _buttonAudioRecordAgain.setVisibility(View.VISIBLE);

								/* Permit play audio */
								_buttonAudioRecordPlay.setVisibility(View.VISIBLE);

							}
						});
					}
				}
			});

			_buttonAudioRecordPlay.setOnClickListener(new OnClickListener()
			{

				public void onClick(View arg0)
				{

					FileInputStream fileAudioInputStream = getAudioInputStream();

					/* Play audio */
					try
					{
						int duration = SoundPlay.play(fileAudioInputStream.getFD());
						TimerTask timerTask = new TimerTask()
						{
							@Override
							public void run()
							{
								AppMain._codeResultService = CodeResult.STOP_PLAY_AUDIO;
								AppMain.callOnWindowFocusChange(AddReportActivity.this);
								return;
							}
						};

						_timerStopPlayAudio = new Timer();
						_timerStopPlayAudio.schedule(timerTask, duration);

					} catch (Exception e)
					{
						AppMain._codeResultService = CodeResult.FAIL_PLAY_AUDIO;
						AppMain.callOnWindowFocusChange(AddReportActivity.this);
						e.printStackTrace();
						return;
					}

					_buttonAudioRecordPlay.setVisibility(View.GONE);
					_buttonAudioRecordAgain.setVisibility(View.GONE);
					_buttonAudioRecordPlayStop.setVisibility(View.VISIBLE);

				}
			});

			_buttonAudioRecordPlayStop.setOnClickListener(new OnClickListener()
			{
				public void onClick(View arg0)
				{
					AppMain._codeResultService = CodeResult.STOP_PLAY_AUDIO;
					AppMain.callOnWindowFocusChange(AddReportActivity.this);
					return;
				}
			});

			_buttonAudioRecordAgain.setOnClickListener(new OnClickListener()
			{

				public void onClick(View v)
				{

					// AppMain.debug("audio file: " +
					// _fileAudio.getAbsolutePath());

					if (!Config.USE_AUDIO_RECORD_BUILD_IN)
					{
						// _audioRecorder = new
						// AudioRecorder(AppMain.DIRECTORY_AUDIO_FILE
						// + AppMain.AUDIO_FILE_NAME_DEFAULT);

						// _audioRecorder = ExtAudioRecorder.getInstanse(false);

						_audioRecorder = new RecorderWave();
					}

					if (Config.USE_AUDIO_RECORD_BUILD_IN)
					{
						Intent intent = new Intent(
								MediaStore.Audio.Media.RECORD_SOUND_ACTION);
						startActivityForResult(intent,
								AppMain.REQUEST_AUDIO_RECORD);

					}
					else
					{

						try
						{
							// _audioRecorder.setOutputFile(_fileAudio.getAbsolutePath());

							_audioRecorder.startRecording();

						} catch (Exception e)
						{
							AppMain._codeResultService = CodeResult.SD_CARD_NOT_FOUND;
							AppMain.callOnWindowFocusChange(AddReportActivity.this);
							e.printStackTrace();
							return;
						}

						_textTimeRecordCountDown.setVisibility(View.VISIBLE);

						new CountDownTimer(RecorderWave.MAX_RECORD_TIME, 1000)
						{

							@Override
							public void onTick(long millisUntilFinished)
							{
								_textTimeRecordCountDown.setText(getStringTimeShow(millisUntilFinished));
							}

							@Override
							public void onFinish()
							{
								_textTimeRecordCountDown.setVisibility(View.GONE);
								AppMain._codeResultService = CodeResult.STOP_RECORD_AUDIO;
								AppMain.callOnWindowFocusChange(AddReportActivity.this);
								return;
							}
						}.start();

						_buttonAudioRecordAgain.setVisibility(View.GONE);
						_buttonAudioRecordStop.setVisibility(View.VISIBLE);
						_buttonAudioRecordPlay.setVisibility(View.GONE);
					}
				}
			});

		}
		AppMain._isDoneLoading = false;

		// AppMain.registerGPS(this);

	}

	private String getStringTimeShow(long timeMillis)
	{
		int secondTimes = (int) (timeMillis / 1000);
		String time = "";

		int hour = (int) (secondTimes / (60 * 60));
		String hourString = "" + (hour > 9 ? hour : ("0" + hour));
		time += hourString;

		int minite = (int) (secondTimes / (60));
		String miniteString = ":" + (minite > 9 ? minite : ("0" + minite));
		time += miniteString;

		int second = (int) (secondTimes % (60));
		String secondString = ":" + (second > 9 ? second : ("0" + second));
		time += secondString;

		return time;
	}

	private FileInputStream getAudioInputStream()
	{
		if (_audioRecorder == null)
			return null;
		FileInputStream fileAudioInputStream = null;
		try
		{
			// _fileAudioInputStream = new
			// FileInputStream(_fileAudio.getAbsolutePath());
			fileAudioInputStream = new FileInputStream(
					_audioRecorder.getFileName());
		} catch (FileNotFoundException e1)
		{
			e1.printStackTrace();
		}

		if (fileAudioInputStream == null)
		{
			AppMain._codeResultService = CodeResult.FAIL_RECORD_AUDIO;
			AppMain.callOnWindowFocusChange(AddReportActivity.this);
			_buttonAudioRecord.setVisibility(View.VISIBLE);
			return null;
		}

		try
		{
			if (fileAudioInputStream.available() > AppMain.MAX_FILE_SIZE)
			{
				AppMain._codeResultService = CodeResult.FILE_TOO_LARGE;
				AppMain.callOnWindowFocusChange(AddReportActivity.this);
				_buttonAudioRecord.setVisibility(View.VISIBLE);
				return null;
			}
		} catch (IOException e1)
		{
			e1.printStackTrace();
		}
		_fileAudioGeneral = new FileGeneral();
		_fileAudioGeneral.setOriginalName(_audioRecorder.getName());
		_fileAudioGeneral.setPath(_audioRecorder.getFolder());
		return fileAudioInputStream;
	}

	private void showProgressBar()
	{
		AppMain.showProgress(this);
		enableAllClick(false);
	}

	private void enableAllClick(boolean enable)
	{
		_buttonImage.setClickable(enable);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		if (AppMain._isDoneLoading)
		{
			switch (AppMain._codeResultService)
			{
			case ERROR_OUT_OF_MEMORY:
				AppMain.showAlert(this,
						R.string.textErrorDataTooLargeCanNotLoad, true);
				break;
			case SUCCESS_ADD_COMMENT:
				AppMain.showAlert(this, R.string.textMessageAddCommentSuccess,
						true);
				break;
			case FAIL_ADD_COMMENT:
				AppMain.showAlert(this, R.string.textMessageAddCommentFail,
						true);
				break;
			case TEXT_INPUT_EMPTY:
				AppMain.showAlert(this, getString(R.string.textErrorEmptyInput)
						+ " " + getString(R.string.textContentLowercase), false);
				break;
			default:
				break;
			}
			AppMain._isDoneLoading = false;
			enableAllClick(true);
		}

		switch (AppMain._codeResultService)
		{
		case FILE_NOT_FOUND:
			AppMain.showAlert(this, R.string.textErrorFileDamaged, false);
			break;
		case FILE_TOO_LARGE:
			AppMain.showAlert(AddReportActivity.this, String.format(
					getString(R.string.textErrorFileTooLarge),
					(float) AppMain.MAX_FILE_SIZE / 1000000), false);
			break;
		case FAIL_PLAY_AUDIO:
			AppMain.showAlert(this, R.string.textErrorFailPlayAudio, false);
			break;
		case FAIL_RECORD_AUDIO:
			AppMain.showAlert(this, R.string.textErrorFailRecordAudio, false);
			break;
		case STOP_RECORD_AUDIO:
			try
			{
				// _audioRecorder.stop();
				// _audioRecorder.release();

				_audioRecorder.stopRecording();
			} catch (Exception e)
			{
				AppMain._codeResultService = CodeResult.SD_CARD_NOT_FOUND;
				AppMain.callOnWindowFocusChange(AddReportActivity.this);
				e.printStackTrace();
				return;
			}
			_textTimeRecordCountDown.setVisibility(View.GONE);
			_buttonAudioRecordStop.setVisibility(View.GONE);

			/* Permit re-record */
			// _buttonAudioRecordAgain.setVisibility(View.VISIBLE);

			/* Permit play audio */
			_buttonAudioRecordPlay.setVisibility(View.VISIBLE);

			if (getAudioInputStream() == null)
			{
				return;
			}
			break;
		case STOP_PLAY_AUDIO:
			_timerStopPlayAudio.cancel();
			/* Stop play video */
			SoundPlay.stop();

			try
			{
				_buttonAudioRecordPlayStop.setVisibility(View.GONE);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			try
			{
				_buttonAudioRecordPlay.setVisibility(View.VISIBLE);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			// try
			// {
			// _buttonAudioRecordAgain.setVisibility(View.VISIBLE);
			// } catch (Exception e)
			// {
			// e.printStackTrace();
			// }

			try
			{
				_buttonAudioRecordPlay.invalidate();
			} catch (Exception e)
			{
				e.printStackTrace();
			}

			break;
		case SD_CARD_NOT_FOUND:
			AppMain.showAlert(this, R.string.textErrorSDCardNotAvailable, false);
			_buttonAudioRecord.setVisibility(View.VISIBLE);
			_buttonAudioRecordStop.setVisibility(View.GONE);
			_buttonAudioRecordAgain.setVisibility(View.GONE);
			break;

		}

		AppMain._codeResultService = CodeResult.NONE;
		super.onWindowFocusChanged(hasFocus);
	}

	public void alertFinish(String title, String message)
	{
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Back", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent = new Intent();
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		builder.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
		case AppMain.REQUEST_CHOOSE_FILE_IMAGE:
			if (resultCode == RESULT_OK)
			{
				AppMain._imageFileView = AppMain.getBitmapFromIntent(this, data);
				if (AppMain._imageFileView != null)
				{
					Intent intent = new Intent(this, ViewImageActivity.class);
					intent.putExtra("request_type",
							AppMain.REQUEST_CHOOSE_FILE_IMAGE);
					startActivityForResult(intent, AppMain.REQUEST_VIEW_IMAGE);
				}
			}
			break;
		case AppMain.REQUEST_CAMERA:
			if (resultCode == RESULT_OK)
			{
				AppMain._imageFileView = AppMain.closeCamera(this, data);
				if (Config.IS_USE_VIEW_IMAGE)
				{
					Intent intent = new Intent(this, ViewImageActivity.class);
					intent.putExtra("request_type", AppMain.REQUEST_CAMERA);
					startActivityForResult(intent, AppMain.REQUEST_VIEW_IMAGE);
				}
				else
				{
					_fileImage = AppMain._imageFileView;
					AppMain._imageFileView = null;
					_buttonImage.setText(getString(R.string.textViewImage));
					_buttonImage.setVisibility(View.VISIBLE);
					_textImageStatus.setVisibility(View.GONE);
					_buttonImageAgain.setVisibility(View.VISIBLE);
				}
			}
			else
				AppMain._imageFileView = null;
			break;

		case AppMain.REQUEST_VIEW_IMAGE:
			if (resultCode == RESULT_OK)
			{
				_fileImage = AppMain._imageFileView;
				AppMain._imageFileView = null;
				_buttonImage.setText(getString(R.string.textViewImage));
				_buttonImage.setVisibility(View.VISIBLE);
				_textImageStatus.setVisibility(View.GONE);
				_buttonImageAgain.setVisibility(View.VISIBLE);
			}
			break;

		case AppMain.REQUEST_AUDIO_RECORD:
			if (resultCode == RESULT_OK)
			{
				Uri uriSound = data.getData();
				@SuppressWarnings("unused")
				FileInputStream fileAudioInputStream = null;
				try
				{
					fileAudioInputStream = new FileInputStream(
							uriSound.getPath());
				} catch (FileNotFoundException e1)
				{
					e1.printStackTrace();
				}

				_buttonAudioRecordAgain.setVisibility(View.VISIBLE);

				_buttonAudioRecord.setVisibility(View.GONE);

				_buttonAudioRecordPlay.setVisibility(View.VISIBLE);

				// Intent ringIntent = new Intent();
				// ringIntent.setType("audio/mp3");
				// ringIntent.setAction(Intent.ACTION_GET_CONTENT);
				// ringIntent.addCategory(Intent.CATEGORY_OPENABLE);
				// startActivityForResult(Intent.createChooser(ringIntent,
				// "Select Ringtone"), SELECT_RINGTONE);
			}
			else
			{
				AppMain.showAlert(this, R.string.textErrorFailLoadAudio, false);
			}
			break;
		default:
			break;
		}

	}

	@Override
	protected void onDestroy()
	{
		if (Config.USE_AUDIO_RECORD)
		{
			if (_audioRecorder != null && _audioRecorder.isRecording())
				_audioRecorder.stopRecording();
			if (SoundPlay.isPlaying())
				SoundPlay.stop();
		}

		AppMain._imageFileView = null;
		AppMain.hideAllDialog();
		System.gc();
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_option_comment_add, menu);
		return super.onCreateOptionsMenu(menu);
	}

	private void doAddReport()
	{
		showProgressBar();
		new Thread(new Runnable()
		{
			public void run()
			{
				String content = _editTextContent.getText().toString().trim();

				FileInputStream fileAudioInputStream = getAudioInputStream();

				if (TextUtils.isEmpty(content) && fileAudioInputStream == null)
				{
					AppMain._codeResultService = CodeResult.TEXT_INPUT_EMPTY;
					AppMain.hideProgressDialog();
					return;
				}
				else
				{
					String imageData = "";
					String audioData = "";

					/* Rename the image name */
					if (_fileImage != null
							&& !TextUtils.isEmpty(_fileImage.getOriginalName()))
					{
						imageData = AppMain.getStringImageData(_fileImage, true);

						String[] names = _fileImage.getOriginalName().split(
								"[.]");
						_fileImage.setName(AppMain.getFileNameFormat(
								AppMain.PREFIX_ADD_COMENT,
								names[names.length - 1]));
					}
					else
					{
						_fileImage = new FileImage(null, "", "", "");
					}

					int totalSize = imageData.length();

					if (Config.USE_AUDIO_RECORD)
					{
						if (fileAudioInputStream != null)
						{
							audioData = AppMain.getStringFileData(_fileAudioGeneral, true);

							if (TextUtils.isEmpty(content))
							{
								content = getString(R.string.textAudioAttach);
							}

							if (TextUtils.isEmpty(audioData))
							{
								_fileAudioGeneral.setName("");
								AppMain.debug("data audio can not load!!!!");
							}
							else
							{
								totalSize += audioData.getBytes().length;
								AppMain.debug("data audio loaded!!!!");
								_fileAudioGeneral.setName(AppMain.getFileNameFormat(
										AppMain.PREFIX_AUDIO,
										AppMain.getFileType(_audioRecorder.getFileName())));
							}
						}
						else
						{
							AppMain.debug("No record audio!");
							_fileAudioGeneral = new FileGeneral("", "", "");
						}
					}

					if (totalSize > AppMain.MAX_FILE_SIZE)
					{
						AppMain.showAlert(
								AddReportActivity.this,
								String.format(
										getString(R.string.textErrorFileTooLarge),
										(float) AppMain.MAX_FILE_SIZE / 1000000),
								false);
						return;
					}

					AppMain._imageFileView = null;
					System.gc();

					String resultAddComment = null;
					boolean isSentData = true;

					if (!Connectivity.isConnectedFast(AddReportActivity.this)
							&& (!TextUtils.isEmpty(imageData) || !TextUtils.isEmpty(audioData)))
					{
						AppMain.debug("Send network slowly!!!");
						resultAddComment = ServiceHelper.doAddCommentLowNetwork(
								AppMain.getCurrentTask().getId(), content,
								AppMain._user.getMemberId(),
								AppMain._currentLatitude,
								AppMain._currentLongitude);

						if (!TextUtils.isEmpty(_fileAudioGeneral.getName()))
						{
							_audioRecorder.copyWaveFile(
									_fileAudioGeneral.getPath()
											+ "/"
											+ _fileAudioGeneral.getOriginalName(),
									_fileAudioGeneral.getPath() + "/"
											+ _fileAudioGeneral.getName());
						}

						File file = new File(_fileImage.getPath() + "/"
								+ _fileImage.getOriginalName());

						if (!TextUtils.isEmpty(_fileImage.getName())
								&& _fileImage.getBitmap() != null
								&& !file.exists())
						{
							FileOutputStream fileOutputStream;
							try
							{
								fileOutputStream = new FileOutputStream(file);
								_fileImage.getBitmap().compress(
										CompressFormat.JPEG, 100,
										fileOutputStream);
							} catch (FileNotFoundException e)
							{
								e.printStackTrace();
							}
						}

						isSentData = false;
					}
					else
					{
						AppMain.debug("ServiceHelper.doAddComment(AppMain.getCurrentTask().getId() = "
								+ AppMain.getCurrentTask().getId()
								+ ", "
								+ "content = "
								+ content
								+ ", AppMain._user.getMemberId() = "
								+ AppMain._user.getMemberId()
								+ ", imageName = "
								+ _fileImage.getName()
								+ ", "
								+ "imageData, audioStringName = "
								+ _fileAudioGeneral.getName()
								+ ", "
								+ "audioData, AppMain._currentLatitude = "
								+ AppMain._currentLatitude
								+ ", AppMain._currentLongitude = "
								+ AppMain._currentLongitude + ")");

						resultAddComment = ServiceHelper.doAddReport(
								AppMain.getCurrentTask().getId(), content,
								AppMain._user.getMemberId(),
								_fileImage.getName(), imageData,
								_fileAudioGeneral.getName(), audioData,
								AppMain._currentLatitude,
								AppMain._currentLongitude);
					}

					if (resultAddComment.equals(ServiceHelper.ERROR_OUT_OF_MEMORY))
					{
						AppMain._codeResultService = CodeResult.ERROR_OUT_OF_MEMORY;
						AppMain.hideProgressDialog();
						return;
					}

					String[] splitString = resultAddComment.split("[,]");

					if (splitString[0].equalsIgnoreCase(ServiceHelper.RESULT_OK))
					{
						AppMain._codeResultService = CodeResult.SUCCESS_ADD_COMMENT;

						// save comment
						Report reportAdded = null;
						reportAdded = new Report();
						reportAdded.setContent(content);
						reportAdded.setFileImage(TextUtils.isEmpty(_fileImage.getName()) ? null
								: new FileImage(null, _fileImage.getName(),
										_fileImage.getOriginalName(),
										_fileImage.getPath()));
						reportAdded.setSender(AppMain._user.getMemberName() == null ? ""
								: AppMain._user.getMemberName());
						reportAdded.setTaskId(AppMain.getCurrentTask().getId() == null ? ""
								: AppMain.getCurrentTask().getId());
						reportAdded.setFileAudio(_fileAudioGeneral);
						reportAdded.setSyncData(isSentData);

						String date = null;
						if (splitString.length == 3)
						{
							date = splitString[1];
							reportAdded.setId(splitString[2]);
						}
						else
						{
							Date d = new Date();
							DateFormat dateFormat = new SimpleDateFormat(
									"dd/MM/yyyy kk:mm");
							date = dateFormat.format(d);
						}

						reportAdded.setDateCreate(date == null ? "" : date);

						ReportSQLite reportSQLite = new ReportSQLite(
								AddReportActivity.this);
						reportSQLite.insert(reportAdded);

						AppMain._listComments.add(0, reportAdded);
					}
					else
					{
						AppMain._codeResultService = CodeResult.FAIL_ADD_COMMENT;
					}
					AppMain.hideProgressDialog();
				}
			}
		}).start();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.menuItemAcount)
		{
			AppMain.showDialogList(this, AppMain.DIALOG_ACCOUNT);
		}
		else if (item.getItemId() == R.id.menuItemSkype)
		{
			AppMain.startSkype(this);
		}
		else if (item.getItemId() == R.id.menuItemSaveComment)
		{
			if (Config.USE_AUDIO_RECORD)
			{
				if (_audioRecorder != null && _audioRecorder.isRecording())
				{
					AppMain._codeResultService = CodeResult.STOP_RECORD_AUDIO;
					AppMain.callOnWindowFocusChange(this);
				}

				if (SoundPlay.isPlaying())
				{
					AppMain._codeResultService = CodeResult.STOP_PLAY_AUDIO;
					AppMain.callOnWindowFocusChange(this);
				}

			}

			LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
			{
				OnClickListener onClickListenerYES = new OnClickListener()
				{
					public void onClick(View v)
					{
						AppMain.hideAllDialog();
						// Launch settings, allowing user to
						// make a change
						Intent i = new Intent(
								Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						startActivity(i);
					}
				};

				OnClickListener onClickListenerNO = new OnClickListener()
				{
					public void onClick(View v)
					{
						AppMain.hideAllDialog();
						doAddReport();
					}
				};
				AppMain.showAlert(AddReportActivity.this,
						R.string.textMessageEnableGPS, false,
						onClickListenerYES, onClickListenerNO);
			}
			else
			{
				doAddReport();
			}
		}
		return true;
	}

	public void processDialogListChoosingImage(int position)
	{
		switch (position)
		{
		case AppMain.IMAGE_BROWSE:
			if (!AppMain.isSdCardPresent())
			{
				AppMain.showAlert(this, R.string.textErrorSDCardNotAvailable,
						false);
			}
			else
			{
				AppMain.showFileChooser(this, AppMain.REQUEST_CHOOSE_FILE_IMAGE);
			}
			break;
		case AppMain.IMAGE_TAKE_CAMERA:
			// Intent intent = new Intent(this, CameraActivity.class);
			// startActivityForResult(intent, AppMain.REQUEST_CAMERA);

			AppMain.openCamera(this);

			break;
		default:
			break;
		}
	}

	@TargetApi(5)
	@Override
	public void onBackPressed()
	{
		// AppMain.removeGPS();
		if (!_editTextContent.getText().toString().trim().endsWith(""))
		{
			OnClickListener onClickListenerYES = new OnClickListener()
			{
				public void onClick(View v)
				{
					finish();
				}
			};
			AppMain.showAlert(this, R.string.textMessageAskForSaveComment,
					false, onClickListenerYES);
		}
		else
			super.onBackPressed();
	}
}
